package com.base.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class JacksonUtil {

    private static final Logger logger = LoggerFactory.getLogger(JacksonUtil.class);

    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static String objToJson(Object obj){
        String json = null;
        try {
            json = objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            logger.error("obj->json转换错误：{}",e);
        }

        return json;
    }

    public static <T>T jsonToObject(String json,Class<T> clazz){
        T t = null;
        try {
            t=objectMapper.readValue(json,clazz);
        } catch (IOException e) {
            logger.error("json->obj转换错误：{}",e);
        }
        return t;
    }

    public static List<?> jsonToList(String json, Class<?> clazz){
        List<?> t = null;
        try {
            JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, clazz);
            t=objectMapper.readValue(json,javaType);
        } catch (IOException e) {
            logger.error("json->list转换错误：{}",e);
        }
        return t;
    }

    public static Map<String,Object> fastJsonToMap(String json){
        try{
            Map<String,Object> map = jsonToObject(json,Map.class);
            for(Map.Entry<String,Object> m:map.entrySet()){
                if(m.getValue() != null && (m.getValue() instanceof Collection || m.getValue() instanceof Map)){
                    m.setValue(objToJson(m.getValue()));
                }
            }
            return map;
        }catch (Exception e){

        }
        return null;
    }
}
